﻿// -----------------------------------------------------------------------------
// 园丁,是个很简单的管理系统
//  gitee:https://gitee.com/hgflydream/Gardener 
//  issues:https://gitee.com/hgflydream/Gardener/issues 
// -----------------------------------------------------------------------------

using Gardener.Enums;
using Gardener.VerifyCode.Dtos;
using Gardener.VerifyCode.Enums;
using Gardener.VerifyCode.Services;
using Microsoft.AspNetCore.Components;
using System.Threading.Tasks;

namespace Gardener.Client.Base.Components
{
    public partial class ImageVerifyCode
    {
        [Inject]
        private IImageVerifyCodeService verifyCodeService { get; set; }
        private string verifyCodeImage = "";

        [Parameter]
        public string Style { get; set; } = "height:38px;margin-left:2px;";
        /// <summary>
        /// 字符集类型
        /// </summary>
        [Parameter]
        public CodeCharacterTypeEnum? Type { get; set; }
        /// <summary>
        /// 校验码字符数量
        /// </summary>
        [Parameter]
        public int? CharacterCount { get; set; }
        /// <summary>
        /// 字符大小
        /// </summary>
        [Parameter]
        public int? FontSize { get; set; }
        [Parameter]
        public string VerifyCodeKey { get; set; }
        [Parameter]
        public EventCallback<string> VerifyCodeKeyChanged { get; set; }

        private bool isLoading = false;

        protected override async Task OnInitializedAsync()
        {
            await ReLoadVerifyCode();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task ReLoadVerifyCode()
        {
            isLoading = true;
            //移除上次的验证码
            if (!string.IsNullOrEmpty(VerifyCodeKey))
            {
                await verifyCodeService.Remove(VerifyCodeKey);
            }
            ImageVerifyCodeInput input = new ImageVerifyCodeInput() 
            {
                FontSize=FontSize,
                CreateCodeParam=new CharacterCodeCreateParam 
                {
                    Type=Type,
                    CharacterCount= CharacterCount
                }
            }; 
            ImageVerifyCodeOutput output =await verifyCodeService.Create(input);
            if (output != null)
            {
                VerifyCodeKey = output.Key;
                await VerifyCodeKeyChanged.InvokeAsync(VerifyCodeKey);
                verifyCodeImage = "data:image/gif;base64," + output.Base64Image;
            }
            isLoading = false;
        }
    }
}
